<?php

namespace Izqut\Membership\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;

class UserMembership extends Model
{
    protected $fillable = [
        'user_id',
        'membership_id',
        'starts_at',
        'expires_at',
        'is_active',
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'expires_at' => 'datetime',
        'is_active' => 'boolean',
    ];

    /**
     * Get the user that owns the membership
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(config('membership.user_model'));
    }

    /**
     * Get the membership plan
     */
    public function membership(): BelongsTo
    {
        return $this->belongsTo(Membership::class);
    }

    /**
     * Check if membership is currently active
     */
    public function isActive(): bool
    {
        if (!$this->is_active) {
            return false;
        }

        if ($this->isExpired()) {
            $this->deactivate();
            return false;
        }

        return true;
    }

    /**
     * Check if membership has expired
     */
    public function isExpired(): bool
    {
        if (is_null($this->expires_at)) {
            return false; // Perpetual membership
        }

        return $this->expires_at->isPast();
    }

    /**
     * Get days remaining until expiration
     */
    public function daysRemaining(): ?int
    {
        if (is_null($this->expires_at)) {
            return null; // Perpetual
        }

        return max(0, now()->diffInDays($this->expires_at, false));
    }

    /**
     * Deactivate the membership
     */
    public function deactivate(): void
    {
        $this->update(['is_active' => false]);
    }

    /**
     * Activate the membership
     */
    public function activate(): void
    {
        $this->update(['is_active' => true]);
    }

    /**
     * Scope: only active memberships
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            });
    }

    /**
     * Scope: only expired memberships
     */
    public function scopeExpired($query)
    {
        return $query->whereNotNull('expires_at')
            ->where('expires_at', '<=', now());
    }

    /**
     * Scope: expiring soon (within specified days)
     */
    public function scopeExpiringSoon($query, int $days = 7)
    {
        return $query->whereNotNull('expires_at')
            ->whereBetween('expires_at', [now(), now()->addDays($days)]);
    }
}
